package com.haoji.upload.common.Value.mvc;

import org.springframework.core.convert.converter.Converter;

import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Date;
import java.util.List;
import java.util.regex.Pattern;

/**
 * @program: upload
 * @description:
 * @author: xiaolei
 * @create: 2021-04-15 16:30
 **/
public class StringToDateConverter implements Converter<String, Date> {

    private static List<String> formats = new ArrayList<>(4);

    static {
        //Collections.unmodifiableList(formats);
        formats.add("yyyy-MM");
        formats.add("yyyy-MM-dd");
        formats.add("yyyy-MM-dd HH:mm");
        formats.add("yyyy-MM-dd HH:mm:ss");
    }

    @Override
    public Date convert(String s) {
        String value = s.trim();
        if ("".equals(value) || "null".equals(value))
            return null;
        if (Pattern.compile("[0-9]{4}-[0-9]{2}").matcher(value).matches())
            return parseDate(s, formats.get(0));
        else if (Pattern.compile("[0-9]{4}-[0-9]{2}-[0-9]{2}").matcher(value).matches())
            return parseDate(s, formats.get(1));
        else if (Pattern.compile("[0-9]{4}-[0-9]{2}-[0-9]{2} [0-9]{2}:[0-9]{2}").matcher(value).matches())
            return parseDate(s, formats.get(2));
        else if (Pattern.compile("[0-9]{4}-[0-9]{2}-[0-9]{2} [0-9]{2}:[0-9]{2}:[0-9]{2}").matcher(value).matches())
            return parseDate(s, formats.get(3));
        else
            throw new IllegalArgumentException("Invalid date value '" + s + "'");
    }

    public Date parseDate(String dateStr, String format)
    {
        Date date = null;
        try
        {
            DateFormat dateFormat = new SimpleDateFormat(format);
            date = dateFormat.parse(dateStr);
        } catch (Exception e)
        {

        }
        return date;
    }
}
